package org.bjou
import org.apache.shiro.crypto.hash.Sha256Hash
import org.springframework.dao.DataIntegrityViolationException

class ShiroUserController {

    static allowedMethods = [save: "POST", update: "POST", delete: "POST"]

    def index() {
        redirect(action: "list", params: params)
    }
    
    //重置密码
    def init()
    {
         def shiroUserInstance = ShiroUser.get(params.id)
         shiroUserInstance.passwordHash =  new Sha256Hash("123456").toHex()
          flash.message = "密码已被重置为123456"
          shiroUserInstance.save(flush: true)
         redirect(action: "list")
    }
    
    

    def list() {
        params.max = Math.min(params.max ? params.int('max') : 10, 100)
        
         def cel = {  
            if(params.fullname){  
                //TODO
                sqlRestriction ("id in  (select user_id from user_baseinfo where fullname like '%"+params.fullname+"%' )")
            }
            if(params.roleId){  
                sqlRestriction ("id in  (select shiro_user_id from shiro_user_roles where shiro_role_id = "+params.roleId+")")
            }
            if(params.groupId){  
                sqlRestriction ("id in  (select user_id from user_baseinfo where user_group_id = "+params.groupId+")")
            }
         }
         
        def userList = ShiroUser.createCriteria().list(params,cel) 
        
         def tocJson=[]
        userList.each{ ch ->
            def chJson= [:]
             chJson['id'] = ch.id
             
            //去找基础信息
            def ubiInstance  = UserBaseinfo.findByUser(ch)
            chJson['fullname'] = ubiInstance?.fullname
            chJson['username'] = ch["username"]
            chJson['groupname'] =  ubiInstance?.userGroup?.groupName
             chJson['rolename'] =  ShiroRole.findByUser(ch.id).list()?.get(0)?.name
          
            
            tocJson << chJson
        }
         def totalRows = ShiroUser.createCriteria().list(cel).size()
        
        [shiroUserInstanceList: tocJson, shiroUserInstanceTotal: totalRows]
    }

    def create() {
        [shiroUserInstance: new ShiroUser(params)]
    }

    def save() {
        params.passwordHash = "123456"
        params.passwordHash = new Sha256Hash(params.passwordHash).toHex()
        def shiroUserInstance = new ShiroUser(params)
        print params
        if(params.roleId&&params.roleId!="")
        {
             def roleInstance = ShiroRole.findById(params.roleId.toLong())
             print roleInstance
            
             shiroUserInstance.addToRoles(roleInstance)
        }
        else
            {
                flash.message ="请选择角色"
               render(view: "create", model: [shiroUserInstance: shiroUserInstance])
                return
            }
        
       
        if (!shiroUserInstance.save(flush: true)) {
            
            render(view: "create", model: [shiroUserInstance: shiroUserInstance])
            return
        }
        
        //userbaseinfo
        def userBaseinfoInstance = new UserBaseinfo(fullname:params.fullname)
        userBaseinfoInstance.setUser(shiroUserInstance)
        userBaseinfoInstance.save(flush: true)
       
        

	//flash.message = message(code: 'default.created.message', args: [message(code: 'shiroUser.label', default: 'ShiroUser'), shiroUserInstance.fullname])
        flash.message = "新建用户成功,用户名为"+params.username+",初始密码为123456"
        redirect(action: "list")
        
     
    }

    def show() {
        def ch = ShiroUser.get(params.id)
        
         def shiroUserInstance = ShiroUser.get(params.id)
        def departmentInstance
        def branchInstance
        def roleInstance = ShiroRole.findByUser(shiroUserInstance.id).list()?.get(0)
        
        if(roleInstance?.name=="分校角色")
        {
            // branchInstance = new Branch()
            if(Branch.findByUser(shiroUserInstance.id).list().size()>0)
            {
            branchInstance = Branch.findByUser(shiroUserInstance.id).list()?.get(0)
            }
        }
        
        if(roleInstance?.name=="系部角色")
        {
            //departmentInstance = new Department()
            if(Department.findByUser(shiroUserInstance.id).list().size()>0)
            {
                departmentInstance = Department.findByUser(shiroUserInstance.id).list()?.get(0)
            }
            
        }
        
        if (!ch) {
			flash.message = message(code: 'default.not.found.message', args: [message(code: 'shiroUser.label', default: 'ShiroUser'), params.id])
            redirect(action: "list")
            return
        }
        
         def chJson= [:]
             chJson['id'] = ch.id
             
            //去找基础信息
            def ubiInstance  = UserBaseinfo.findByUser(ch)
            chJson['fullname'] = ubiInstance?.fullname
            chJson['username'] = ch["username"]
            chJson['groupname'] =  ubiInstance?.userGroup?.groupName
             chJson['rolename'] =  ShiroRole.findByUser(ch.id).list()?.get(0)?.name
        
        

        [shiroUserInstance: chJson,branchInstance:branchInstance,departmentInstance:departmentInstance]
    }

    def edit() {
        def shiroUserInstance = ShiroUser.get(params.id)
        def departmentInstance
        def branchInstance
        def roleInstance = ShiroRole.findByUser(shiroUserInstance.id).list()?.get(0)
        
        if(roleInstance?.name=="分校角色")
        {
            // branchInstance = new Branch()
            if(Branch.findByUser(shiroUserInstance.id).list().size()>0)
            {
            branchInstance = Branch.findByUser(shiroUserInstance.id).list()?.get(0)
            }
        }
        
        if(roleInstance?.name=="系部角色")
        {
            //departmentInstance = new Department()
            if(Department.findByUser(shiroUserInstance.id).list().size()>0)
            {
                departmentInstance = Department.findByUser(shiroUserInstance.id).list()?.get(0)
            }
            
        }
        
        
        if (!shiroUserInstance) {
            flash.message = message(code: 'default.not.found.message', args: [message(code: 'shiroUser.label', default: 'ShiroUser'), params.id])
            redirect(action: "list")
            return
        }

        [shiroUserInstance: shiroUserInstance,branchInstance:branchInstance,departmentInstance:departmentInstance,roleInstance:roleInstance]
    }

    def update() {
        def shiroUserInstance = ShiroUser.get(params.id.toLong())
        if (!shiroUserInstance) {
            flash.message = message(code: 'default.not.found.message', args: [message(code: 'shiroUser.label', default: 'ShiroUser'), params.id])
            redirect(action: "list")
            return
        }

        if (params.version) {
            def version = params.version.toLong()
            if (shiroUserInstance.version > version) {
                shiroUserInstance.errors.rejectValue("version", "default.optimistic.locking.failure",
                          [message(code: 'shiroUser.label', default: 'ShiroUser')] as Object[],
                          "Another user has updated this ShiroUser while you were editing")
                render(view: "edit", model: [shiroUserInstance: shiroUserInstance])
                return
            }
        }

        shiroUserInstance.properties = params
        
        

        if (!shiroUserInstance.save(flush: true)) {
            render(view: "edit", model: [shiroUserInstance: shiroUserInstance])
            return
        }
        
        
        
       if(params.branchId)
        {
            //println shiroUserInstance.branch 
            def oldBranchInstance = Branch.findByUser(shiroUserInstance.id).list()?.get(0)
            oldBranchInstance.removeFromUsers(shiroUserInstance)
            
            //println params.branchId
            def newBranchInstance = Branch.get(params.branchId)
            
            newBranchInstance.addToUsers(shiroUserInstance)
            newBranchInstance.save(flush: true)
        }
        
        
        if(params.departmentId)
        {
            //println shiroUserInstance.branch
             if(Department.findByUser(shiroUserInstance.id).list().size()>0)
            {
            def oldDepartmentInstance = Department.findByUser(shiroUserInstance.id).list()?.get(0)
            oldDepartmentInstance.removeFromUsers(shiroUserInstance)
            }
            
            //println params.branchId
            def newDepartmentInstance = Department.get(params.departmentId)
            
            newDepartmentInstance.addToUsers(shiroUserInstance)
            newDepartmentInstance.save(flush: true)
        }
        
        
        

		flash.message = message(code: 'default.updated.message', args: [message(code: 'shiroUser.label', default: 'ShiroUser'), shiroUserInstance.id])
        redirect(action: "list")
    }

    def delete() {
        def shiroUserInstance = ShiroUser.get(params.id)
        if (!shiroUserInstance) {
			flash.message = message(code: 'default.not.found.message', args: [message(code: 'shiroUser.label', default: 'ShiroUser'), params.id])
            redirect(action: "list")
            return
        }

        try {
            shiroUserInstance.delete(flush: true)
			flash.message = message(code: 'default.deleted.message', args: [message(code: 'shiroUser.label', default: 'ShiroUser'), params.id])
            redirect(action: "list")
        }
        catch (DataIntegrityViolationException e) {
			flash.message = message(code: 'default.not.deleted.message', args: [message(code: 'shiroUser.label', default: 'ShiroUser'), params.id])
            redirect(action: "show", id: params.id)
        }
    }
}
